package com.sz.biz.csr.service.impl;

import com.sz.biz.common.constants.CommCodes;
import com.sz.biz.common.constants.ErrorCodes;
import com.sz.biz.common.constants.MessagesCodes;
import com.sz.biz.common.constants.ModuleNames;
import com.sz.biz.common.customer.entity.CusUser;
import com.sz.biz.common.customer.service.CustomerBusinessContactsService;
import com.sz.biz.common.customer.service.CustomerUserService;
import com.sz.biz.csr.constants.CsrConstants;
import com.sz.biz.csr.dto.CsrWorkOrderCustomerIdNameDto;
import com.sz.biz.csr.dto.CsrWorkOrderSchemaDto;
import com.sz.biz.csr.dto.CsrWorkOrderSchemaSaveDto;
import com.sz.biz.csr.dto.CsrWorkOrderTransactionDto;
import com.sz.biz.csr.entity.CsrAskBoardSchema;
import com.sz.biz.csr.entity.CsrWorkOrderSchema;
import com.sz.biz.csr.entity.CsrWorkOrderTransaction;
import com.sz.biz.csr.service.CsrAskBoardSchemaService;
import com.sz.biz.csr.service.CsrWorkOrderSchemaService;
import com.sz.biz.csr.service.CsrWorkOrderTransactionService;
import com.sz.biz.logistics.ord.entity.OrdOrder;
import com.sz.biz.logistics.ord.entity.OrderStatus;
import com.sz.biz.logistics.ord.service.OrdOrderService;
import com.sz.common.base.constants.AppDomain;
import com.sz.common.base.constants.UserActions;
import com.sz.common.base.dao.ParamData;
import com.sz.common.base.dto.CodeNameDto;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.i18n.I18nMessageHelper;
import com.sz.common.base.service.AbstractService;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.core.service.PrincipalLogUtils;
import com.sz.common.core.service.PrincipalUtils;
import com.sz.common.core.system.dto.FileInfoDto;
import com.sz.common.core.system.dto.UserDto;
import com.sz.common.core.system.entity.SysDict;
import com.sz.common.core.system.service.SysDictService;
import com.sz.common.core.system.service.SysFileGroupService;
import com.sz.common.core.system.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * Created by xutao on 17/5/18.
 */
@Service("CsrWorkOrderSchemaService")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class CsrWorkOrderSchemaServiceImpl extends AbstractService implements CsrWorkOrderSchemaService {

    public static final int WORK_ORDER_SCHEMA_TYPE_PRESALES = 0;
    public static final int WORK_ORDER_SCHEMA_TYPE_AFTERSALES = 1;
    public static final int WORK_ORDER_SCHEMA_TYPE_WAYBILL = 2;
    public static final int WORK_ORDER_SCHEMA_TYPE_OTHERS = 3;
    /**
     * 订单阻塞性工单
     */
    public static final int WORK_ORDER_SCHEMA_TYPE_AFFECT_WAYBILL = 4;

    @Autowired
    OrdOrderService ordOrderService;

    @Autowired
    SysFileGroupService fileGroupService;

    @Autowired
    CsrAskBoardSchemaService csrAskBoardSchemaService;

    @Autowired
    SysDictService sysDictService;

    @Autowired
    CustomerUserService customerUserService;

    @Autowired
    UserService userService;

    @Autowired
    CsrWorkOrderTransactionService csrWorkOrderTransactionService;

    @Autowired
    private CustomerBusinessContactsService customerBusinessContactsService;

    @Override
    protected String getMapperNamespace() {
        return "CsrWorkOrderSchemaMapper";
    }

    @Override
    public int save(CsrWorkOrderSchemaSaveDto entry) {
        int id = 0;
        if (entry != null) {
            checkDataValid(entry);
            entry.setCreator(PrincipalUtils.getAccountId());
            entry.setWorkOrderCode(generateNewUid());
            entry.setStatus(0);
            List<String> attachments = entry.getAttachFileIds();
            if (!CollectionUtils.isEmpty(attachments)) {
                String fileGroupId = fileGroupService.createFileGroup(attachments,
                        "biz.customer.workorder", "客服工单编号:" + entry.getWorkOrderCode() + "上传工单附件", AppDomain.OPERATION);
                entry.setFileGroupId(fileGroupId);
            }
            entry.setCreator(PrincipalUtils.getAccountId());
            if (entry.getType() == WORK_ORDER_SCHEMA_TYPE_WAYBILL || entry.getType() == WORK_ORDER_SCHEMA_TYPE_AFFECT_WAYBILL) {
                String orderNo = ordOrderService.findOrderNoByWaybillNo(entry.getWaybillNo());
                OrdOrder ordOrder = ordOrderService.findByOrderNo(orderNo);
                if (ordOrder != null && !ordOrder.getOrderStatus().equals(OrderStatus.DRAFT)) {
                    entry.setOrderNo(ordOrder.getOrderNo());
                    entry.setCustomerUserId(ordOrder.getCusUserId());
                } else {
                    throw Exceptions.bizException(com.sz.biz.logistics.constants.ErrorCodes.ERROR_WAYBILLNO_NOT_EXIST);
                }
            } else if (entry.getType() == WORK_ORDER_SCHEMA_TYPE_PRESALES || entry.getType() == WORK_ORDER_SCHEMA_TYPE_AFTERSALES) {
                CsrAskBoardSchema csrAskBoardSchema = csrAskBoardSchemaService.findById(entry.getRefAskBoardId());
                if (csrAskBoardSchema != null) {
                    entry.setCustomerUserId(csrAskBoardSchema.getRefCustomerId());
                }
            }

            CsrWorkOrderSchema csrWorkOrderSchema = new CsrWorkOrderSchema();
            BeanUtils.copyProperties(entry, csrWorkOrderSchema);
            dao.save(getSqlName("insertSelective"), csrWorkOrderSchema);
            CsrWorkOrderTransactionDto csrWorkOrderTransactionDto = new CsrWorkOrderTransactionDto();
            csrWorkOrderTransactionDto.setTransactor(csrWorkOrderSchema.getCreator());
            csrWorkOrderTransactionDto.setAction(5);
            csrWorkOrderTransactionDto.setRefWorkorderId(csrWorkOrderSchema.getId());
            csrWorkOrderTransactionDto.setSuggest("");
//            csrWorkOrderTransactionDto.setSuggest(csrWorkOrderSchema.getContent());
            csrWorkOrderTransactionDto.setSendTo(csrWorkOrderSchema.getTransactor());
            csrWorkOrderTransactionService.save(csrWorkOrderTransactionDto);

            //保存操作日志
            Map<String, Object> dataBackup = new HashMap<>();
            dataBackup.put("ADD_CUSTOMERSERVICE_WORKORDER_SCHEMA", entry);
            PrincipalLogUtils.addOperationLog(ModuleNames.CSR, ModuleNames.CSR_WORK_ORDER, UserActions.ADD, "新增工单", dataBackup);

            id = csrWorkOrderSchema.getId();
        }

        return id;
    }

    @Override
    public void update(CsrWorkOrderSchema csrWorkOrderSchema) {
        if (csrWorkOrderSchema != null) {
            if (csrWorkOrderSchema.getId() != null && csrWorkOrderSchema.getId() > 0) {
                dao.update(getSqlName("updateById"), csrWorkOrderSchema);
                if (csrWorkOrderSchema.getStatus() == CsrConstants.WorkOrderStatus.UNKNOWN) {
                    CsrWorkOrderSchema res = (CsrWorkOrderSchema) dao.findForObject(getSqlName("selectByPrimaryKey"), csrWorkOrderSchema.getId());
                    if (res != null && res.getRefAskBoardId() > 0) {
                        csrAskBoardSchemaService.doneCsrAskBoardById(res.getRefAskBoardId());
                    }
                }
                //保存操作日志
                Map<String, Object> dataBackup = new HashMap<>();
                dataBackup.put("ADD_CUSTOMERSERVICE_WORKORDER_SCHEMA", csrWorkOrderSchema);
                PrincipalLogUtils.addOperationLog(ModuleNames.CSR, ModuleNames.CSR_WORK_ORDER, UserActions.UPDATE, "修改工单", dataBackup);
            }
        }
    }

    @Override
    public QResultDto getWorkOrderTypeList() {
        List<SysDict> sysDictList = sysDictService.findByCatalog("app.csr.workorder.type");
        List<CodeNameDto> codeNameDtoList = new ArrayList<CodeNameDto>();
        for (int i = 0; i < sysDictList.size(); i++) {
            CodeNameDto codeNameDto = new CodeNameDto();
            codeNameDto.setCode(sysDictList.get(i).getCode());
            codeNameDto.setName(sysDictList.get(i).getName());
            codeNameDtoList.add(codeNameDto);
        }
        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(codeNameDtoList);
        return qResultDto;
    }

    @Override
    public int changeWorkOrderStatus(Integer id, Integer status) {

        CsrWorkOrderSchema csrWorkOrderSchema = new CsrWorkOrderSchema();

        csrWorkOrderSchema.setStatus(status);
        csrWorkOrderSchema.setId(id);
        csrWorkOrderSchema.setTransactor(PrincipalUtils.getAccountId());

        dao.update(getSqlName("updateById"), csrWorkOrderSchema);

        if (status == CsrConstants.WorkOrderStatus.UNKNOWN) {

            CsrWorkOrderSchema res = (CsrWorkOrderSchema) dao.findForObject(getSqlName("selectByPrimaryKey"), id);

            if (res != null && res.getRefAskBoardId() > 0) {

                csrAskBoardSchemaService.doneCsrAskBoardById(res.getRefAskBoardId());
            }
        }

        //保存操作日志
        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("CHANGE_CUSTOMERSERVICE_WORKORDER_SCHEMA_STATUS", "id:" + id + " " + "status:" + status);
        PrincipalLogUtils.addOperationLog(ModuleNames.CSR, ModuleNames.CSR_WORK_ORDER, UserActions.UPDATE, "改变工单状态", dataBackup);

        return id;
    }

    @Override
    public QResultDto findWorkOrderList(int pageIndex, int pageSize, String sortName, boolean isAsc,
                                        String workOrderCode, int creator, int customerUserId, Date beginTime,
                                        Date endTime, String title, int status, String customerName, boolean isBlockOrder) {

        List<CsrWorkOrderSchemaDto> csrWorkOrderSchemaDtoList = new ArrayList<CsrWorkOrderSchemaDto>();

        QueryParams params = new QueryParams(pageSize, pageIndex, null, sortName, isAsc, null);
        if (isBlockOrder) {
            params.put("type", WORK_ORDER_SCHEMA_TYPE_AFFECT_WAYBILL);
        }

        params.put("beginTime", beginTime);
        params.put("endTime", endTime);
        params.put("status", status);
        params.put("workOrderCode", workOrderCode);
        params.put("creator", creator);
        params.put("customerUserId", customerUserId);
        params.put("title", title);

        if (creator == 0) {

            params.put("anonymity", customerName);
        }

        if (PrincipalUtils.isRoot()) {

            params.put("workorderList", null);

        } else {

            List<Integer> workorderList = csrWorkOrderTransactionService.findWorkOrderNoByTransactor(PrincipalUtils.getAccountId());

            if (workorderList != null && workorderList.size() > 0) {

                params.put("workorderList", workorderList);
            } else {

                List<Integer> tempList = new ArrayList<Integer>();

                tempList.add(0);

                params.put("workorderList", tempList);
            }
        }


        ParamData pd = this.convertQueryParams(params);

        List<CsrWorkOrderSchema> csrWorkOrderSchemaList = dao.findForList(getSqlName("findByParamListPage"), pd, CsrWorkOrderSchema.class);

        for (int i = 0; i < csrWorkOrderSchemaList.size(); i++) {

            CsrWorkOrderSchemaDto csrWorkOrderSchemaDto = new CsrWorkOrderSchemaDto();

            BeanUtils.copyProperties(csrWorkOrderSchemaList.get(i), csrWorkOrderSchemaDto);

            csrWorkOrderSchemaDto = translateCsrWorkOrderSchemaDto(csrWorkOrderSchemaDto);

            csrWorkOrderSchemaDtoList.add(csrWorkOrderSchemaDto);
        }

        QResultDto qResultDto = new QResultDto();

        qResultDto.setData(csrWorkOrderSchemaDtoList);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    @Override
    public QResultDto findDetailInfoById(Integer id) {
        CsrWorkOrderSchemaDto csrWorkOrderSchemaDto = new CsrWorkOrderSchemaDto();
        CsrWorkOrderSchema csrWorkOrderSchema = (CsrWorkOrderSchema) dao.findForObject(getSqlName("selectByPrimaryKey"), id);
        BeanUtils.copyProperties(csrWorkOrderSchema, csrWorkOrderSchemaDto);
        OrdOrder order = ordOrderService.findByOrderNo(csrWorkOrderSchemaDto.getOrderNo());
        if (!ObjectUtils.isEmpty(order)) {
            csrWorkOrderSchemaDto.setWaybillNo(order.getWaybillNo());
        }
        if (csrWorkOrderSchemaDto.getRefAskBoardId() != null && csrWorkOrderSchemaDto.getRefAskBoardId() > 0) {
            CsrAskBoardSchema tempCsrAskBoardSchema = (CsrAskBoardSchema) dao.findForObject("CsrAskBoardSchemaMapper.selectByPrimaryKey", csrWorkOrderSchemaDto.getRefAskBoardId());
            if (tempCsrAskBoardSchema != null) {
                csrWorkOrderSchemaDto.setAskBoardCode(tempCsrAskBoardSchema.getCode());
                csrWorkOrderSchemaDto.setAskBoardStatus(tempCsrAskBoardSchema.getStatus());
                if (tempCsrAskBoardSchema.getRefCustomerId() != null && tempCsrAskBoardSchema.getRefCustomerId() > 0) {
                    CusUser cusUser = customerUserService.findById(tempCsrAskBoardSchema.getRefCustomerId());
                    if (cusUser != null && cusUser.getFullName() != null) {
                        csrWorkOrderSchemaDto.setAskBoardFullName(cusUser.getFullName());
                    } else {
                        csrWorkOrderSchemaDto.setAskBoardFullName(csrWorkOrderSchemaDto.getAnonymity());
                    }
                }

            }
        }

        csrWorkOrderSchemaDto = translateCsrWorkOrderSchemaDto(csrWorkOrderSchemaDto);
        List<CsrWorkOrderTransaction> csrWorkOrderTransactions = dao.findForList("CsrWorkOrderTransactionMapper.selectByWorkorderId", id, CsrWorkOrderTransaction.class);
        List<CsrWorkOrderTransactionDto> csrWorkOrderTransactionDtoList = new ArrayList<CsrWorkOrderTransactionDto>();
        for (int i = 0; i < csrWorkOrderTransactions.size(); i++) {
            CsrWorkOrderTransactionDto csrWorkOrderTransactionDto = new CsrWorkOrderTransactionDto();
            BeanUtils.copyProperties(csrWorkOrderTransactions.get(i), csrWorkOrderTransactionDto);
            csrWorkOrderTransactionDto = translateCsrWorkOrderTransactionDto(csrWorkOrderTransactionDto);
            csrWorkOrderTransactionDtoList.add(csrWorkOrderTransactionDto);
        }

        csrWorkOrderSchemaDto.setCsrWorkOrderTransactionDtos(csrWorkOrderTransactionDtoList);
        //检测当前用户是否有权限编辑工单
        csrWorkOrderSchemaDto.setEditStatus(false);
        if (PrincipalUtils.isRoot() || csrWorkOrderSchemaDto.getTransactor() == PrincipalUtils.getAccountId()) {
            csrWorkOrderSchemaDto.setEditStatus(true);
        }
        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(csrWorkOrderSchemaDto);
        return qResultDto;
    }

    @Override
    public void batchDelete(List<Integer> ids) {

        if (ids != null && ids.size() > 0) {

            for (int i = 0; i < ids.size(); i++) {

                CsrWorkOrderSchema csrWorkOrderSchema = (CsrWorkOrderSchema) dao.findForObject(getSqlName("selectByPrimaryKey"), ids.get(i));

                if (csrWorkOrderSchema != null) {

                    if (csrWorkOrderSchema.getStatus() != 3) {

                        throw Exceptions.bizException(ErrorCodes.ERROR_CUSTOMER_SERVICE_WORKORDER_DELETED);
                    }
                }
            }

            dao.update(getSqlName("logicDeleteByIds"), ids);
        }

        Map<String, Object> dataBackup = new HashMap<>();
        dataBackup.put("DELETE_CUSTOMERSERVICE_WORKORDER_SCHEMA", ids);
        PrincipalLogUtils.addOperationLog(ModuleNames.CSR, ModuleNames.CSR_ASK_BOARD, UserActions.DELETE, "删除工单", dataBackup);
    }

    @Override
    public Boolean isContainOddNumber(int type, String oddNumber) {

        Boolean ret = false;

        Map<String, Object> map = new HashedMap();

        if (type == CsrConstants.WorkOrderType.QUESTION_FEEDBACK) {

            map.put("refAskBoardId", Integer.valueOf(oddNumber));

        } else if (type == CsrConstants.WorkOrderType.MODIFY_ORDER) {

            map.put("orderNo", oddNumber);
        }

        List<CsrWorkOrderSchema> csrWorkOrderSchemaList = dao.findForList("CsrWorkOrderSchemaMapper.findByAskBoardId", map, CsrWorkOrderSchema.class);

        if (csrWorkOrderSchemaList != null && csrWorkOrderSchemaList.size() > 0) {

            ret = true;
        }

        return ret;
    }

    @Override
    public QResultDto getCustomerList(String q, int pageIndex, int pageSize, String sortName, boolean isAsc, String language) {
        ParamData pd = this.convertQueryParams(new QueryParams(pageSize, pageIndex, q, sortName, isAsc, language));

        List<CsrWorkOrderCustomerIdNameDto> customerIdNameList = dao.findForList(getSqlName("getCustomerListPage"), pd, CsrWorkOrderCustomerIdNameDto.class);


        QResultDto qResultDto = new QResultDto();
        qResultDto.setData(customerIdNameList);
        qResultDto.setPagination(pd.getPagination());

        return qResultDto;
    }

    @Override
    public List<CsrWorkOrderSchema> queryByOrderNo(String orderNo) {
        ParamData pd = new ParamData();
        pd.put("orderNo",orderNo);
        pd.put("status",CsrConstants.WorkOrderStatus.CLOSE);
        return dao.findForList(getSqlName("queryByOrderNo"), pd, CsrWorkOrderSchema.class);
    }


    /**
     * 查询订单的未完成的阻塞性工单
     *
     * @param orderNo 订单号
     * @return 未完成的阻塞性工单集合
     */
    @Override
    public List<CsrWorkOrderSchema> queryBlockByOrderNo(String orderNo) {
        List<CsrWorkOrderSchema> orderSchemas = new ArrayList<>();
        if (!StringUtils.isEmpty(orderNo)) {
            List<CsrWorkOrderSchema> workOrderSchemas = this.queryByOrderNo(orderNo);
            for (CsrWorkOrderSchema workOrderSchema : workOrderSchemas) {
                if (WORK_ORDER_SCHEMA_TYPE_AFFECT_WAYBILL == workOrderSchema.getType()) {
                    if (CsrConstants.WorkOrderStatus.CLOSE != workOrderSchema.getStatus()) {
                        orderSchemas.add(workOrderSchema);

                    }
                }

            }
        }
        return orderSchemas;
    }

    @Override
    public boolean isBlockByOrderNo(String orderNo) {
        boolean isExist = false;
        if (!StringUtils.isEmpty(orderNo)) {
            List<CsrWorkOrderSchema> orderSchemas = this.queryBlockByOrderNo(orderNo);
            if (!CollectionUtils.isEmpty(orderSchemas)) {
                isExist = true;
            }
        }
        return isExist;
    }

    @Override
    public CsrWorkOrderSchema findById(int id) {
        return (CsrWorkOrderSchema) dao.findForObject(getSqlName("queryById"), id);
    }


    public CsrWorkOrderTransactionDto translateCsrWorkOrderTransactionDto(CsrWorkOrderTransactionDto csrWorkOrderTransactionDto) {

        UserDto transactorDto = userService.findUserDetailByUserId(csrWorkOrderTransactionDto.getTransactor());

        if (transactorDto != null) {

            csrWorkOrderTransactionDto.setTransactorUserName(transactorDto.getUserName());
            csrWorkOrderTransactionDto.setTransactorFullName(transactorDto.getFullName());
        }

        if (csrWorkOrderTransactionDto.getSendTo() != null && csrWorkOrderTransactionDto.getSendTo() > 0) {

            UserDto sendToDto = userService.findUserDetailByUserId(csrWorkOrderTransactionDto.getSendTo());

            if (sendToDto != null) {

                csrWorkOrderTransactionDto.setSendToFullName(sendToDto.getFullName());
                csrWorkOrderTransactionDto.setSendToUserName(sendToDto.getUserName());
            }
        }

        int action = csrWorkOrderTransactionDto.getAction();

        if (action == CsrConstants.WorkOrderAction.TRANSFER) {

            csrWorkOrderTransactionDto.setActionName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_HAND_OVER, null));

        } else if (action == CsrConstants.WorkOrderAction.SUBMIT_PROPOSALS) {

            csrWorkOrderTransactionDto.setActionName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_SUBMIT_SUGGESTION, null));

        } else if (action == CsrConstants.WorkOrderAction.ACCEPTED_TREATMENT) {

            csrWorkOrderTransactionDto.setActionName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_ACCEPT_TREAT, null));
        } else if (action == CsrConstants.WorkOrderAction.END) {

            csrWorkOrderTransactionDto.setActionName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_ACCEPT_COMPLETED, null));

        } else if (action == CsrConstants.WorkOrderAction.CLOSE) {

            csrWorkOrderTransactionDto.setActionName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_CLOSED_ORDER, null));

        } else if (action == CsrConstants.WorkOrderAction.CREATE_AND_DELIVER) {

            csrWorkOrderTransactionDto.setActionName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_CREATE_ORDER, null));
        }

        List<FileInfoDto> attachments = fileGroupService.getFileDtosByGroupId(csrWorkOrderTransactionDto.getFileGroupId());

        csrWorkOrderTransactionDto.setFiles(attachments);

        return csrWorkOrderTransactionDto;
    }

    public CsrWorkOrderSchemaDto translateCsrWorkOrderSchemaDto(CsrWorkOrderSchemaDto csrWorkOrderSchemaDto) {

        CusUser cusUser = customerUserService.findById(csrWorkOrderSchemaDto.getCustomerUserId());

        if (cusUser != null) {
            csrWorkOrderSchemaDto.setCustomerUserFullName(cusUser.getFullName());
            csrWorkOrderSchemaDto.setCustomerUserName(cusUser.getUserName());
        }

        UserDto creatorDto = userService.findUserDetailByUserId(csrWorkOrderSchemaDto.getCreator());

        if (creatorDto != null) {

            csrWorkOrderSchemaDto.setCreatorFullName(creatorDto.getFullName());
            csrWorkOrderSchemaDto.setCreatorUserName(creatorDto.getUserName());
        }

        UserDto transactorDto = userService.findUserDetailByUserId(csrWorkOrderSchemaDto.getTransactor());

        if (transactorDto != null) {

            csrWorkOrderSchemaDto.setTransactorFullName(transactorDto.getFullName());
            csrWorkOrderSchemaDto.setTransactorUserName(transactorDto.getUserName());
        }

        if (csrWorkOrderSchemaDto.getType() == 0) {

            csrWorkOrderSchemaDto.setTypeName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_PRE_ADVICE, null));

            if (csrWorkOrderSchemaDto.getCustomerUserId() == 0) {

                CsrAskBoardSchema csrAskBoardSchema = csrAskBoardSchemaService.findById(csrWorkOrderSchemaDto.getRefAskBoardId());

                if (csrAskBoardSchema != null) {

                    csrWorkOrderSchemaDto.setCustomerUserFullName(csrAskBoardSchema.getAnonymity());
                    csrWorkOrderSchemaDto.setCustomerUserName(csrAskBoardSchema.getAnonymity());
                }
            }

        } else if (csrWorkOrderSchemaDto.getType() == 1) {
            csrWorkOrderSchemaDto.setTypeName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_AFTER_SALE_ADVICE, null));
            if (csrWorkOrderSchemaDto.getCustomerUserId() == 0) {
                CsrAskBoardSchema csrAskBoardSchema = csrAskBoardSchemaService.findById(csrWorkOrderSchemaDto.getRefAskBoardId());
                if (csrAskBoardSchema != null) {
                    csrWorkOrderSchemaDto.setCustomerUserFullName(csrAskBoardSchema.getAnonymity());
                    csrWorkOrderSchemaDto.setCustomerUserName(csrAskBoardSchema.getAnonymity());
                }
            }

        } else if (csrWorkOrderSchemaDto.getType() == CsrConstants.WorkOrderType.MODIFY_ORDER) {
            csrWorkOrderSchemaDto.setTypeName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_PROBLEM, null));
        } else if (csrWorkOrderSchemaDto.getType() == CsrConstants.WorkOrderType.OTHERS) {
            csrWorkOrderSchemaDto.setTypeName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_OTHER, null));
        } else if (csrWorkOrderSchemaDto.getType() == CsrConstants.WorkOrderType.UNKNOWN) {
            csrWorkOrderSchemaDto.setTypeName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_BLOCK, null));
        }
        if (csrWorkOrderSchemaDto.getPriority() == CsrConstants.WorkOrderPriority.GENERAL) {
            csrWorkOrderSchemaDto.setPriorityName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_GENERAL, null));
        } else if (csrWorkOrderSchemaDto.getPriority() == CsrConstants.WorkOrderPriority.EMERGENCY) {
            csrWorkOrderSchemaDto.setPriorityName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_URGENT, null));
        } else if (csrWorkOrderSchemaDto.getPriority() == CsrConstants.WorkOrderPriority.VERY_URGENT) {
            csrWorkOrderSchemaDto.setPriorityName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_VERY_URGENT, null));
        }
        if (csrWorkOrderSchemaDto.getStatus() == CsrConstants.WorkOrderStatus.CREATED) {
            csrWorkOrderSchemaDto.setStatusName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_CREATED, null));
        } else if (csrWorkOrderSchemaDto.getStatus() == CsrConstants.WorkOrderStatus.DEALING) {
            csrWorkOrderSchemaDto.setStatusName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_PROCESS, null));
        } else if (csrWorkOrderSchemaDto.getStatus() == CsrConstants.WorkOrderStatus.RESOLVED) {
            csrWorkOrderSchemaDto.setStatusName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_SOLVED, null));
        } else if (csrWorkOrderSchemaDto.getStatus() == CsrConstants.WorkOrderStatus.CLOSE) {
            csrWorkOrderSchemaDto.setStatusName(I18nMessageHelper.getI18nMessage(MessagesCodes.MODULE_WORK_ORDER_CLOSED, null));
        }
        List<FileInfoDto> attachments = fileGroupService.getFileDtosByGroupId(csrWorkOrderSchemaDto.getFileGroupId());
        csrWorkOrderSchemaDto.setFiles(attachments);
        return csrWorkOrderSchemaDto;
    }


    private void checkDataValid(CsrWorkOrderSchemaSaveDto csrWorkOrderSchemaSaveDto) {

        if (csrWorkOrderSchemaSaveDto.getType() == null || csrWorkOrderSchemaSaveDto.getType() < 0) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "type");
        }

        if (StringUtils.isEmpty(csrWorkOrderSchemaSaveDto.getTitle())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "title");
        }

        if (StringUtils.isEmpty(csrWorkOrderSchemaSaveDto.getContent())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "content");
        }

        if (csrWorkOrderSchemaSaveDto.getPriority() < 0 || csrWorkOrderSchemaSaveDto.getPriority() == null) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "priority");
        }

        if (StringUtils.isEmpty(csrWorkOrderSchemaSaveDto.getTransactor())) {

            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY, "trasactor");
        }
    }

    /**
     * 从订单创建工单
     *
     * @param ordOrder
     * @param title
     * @param content
     * @param type
     */
    @Override
    public void saveCsrWorkOrderSchemaByOrd(OrdOrder ordOrder, String title, String content, int type) {
        CsrWorkOrderSchemaSaveDto schemaDto = new CsrWorkOrderSchemaSaveDto();
        schemaDto.setOrderNo(ordOrder.getOrderNo());
        schemaDto.setWaybillNo(ordOrder.getWaybillNo());
        schemaDto.setTitle(title);
        schemaDto.setType(type);
        schemaDto.setContent(content);
        //非常紧急
        schemaDto.setPriority(CommCodes.CSR_WORK_ORDER_PRIORITY_VERY_URGENT);
        schemaDto.setCreator(PrincipalUtils.getAccountId());
        //如果客服没有配置，那么从系统的客服组里随机取一个。
        int bussContactId = getCsrWorkBussContactId(ordOrder.getCustomerId(), CommCodes.CUS_BUS_CONTACT_SYS_GROUP_CSD);
        schemaDto.setTransactor(bussContactId);
        //客户的信息
        CusUser cusUser = customerUserService.findById(ordOrder.getCusUserId());
        if (!ObjectUtils.isEmpty(cusUser)) {
            schemaDto.setAnonymity(cusUser.getUserName());
            schemaDto.setAnonyTel(cusUser.getMobilePhone());
            schemaDto.setCustomerUserId(cusUser.getId());
        }
        this.save(schemaDto);
    }

    /**
     * 根据客户的账户id、系统的组的编码(组织或分组的编码)，查询一个随机的用户
     *
     * @param customerId 客户的id
     * @param groupCode  组织或分组的编码
     * @return 查询到的随机用户id
     */
    private int getCsrWorkBussContactId(int customerId, String groupCode) {
        int bussContactId = customerBusinessContactsService.findRandomBussIdByCustomerIdAndGroupCode(customerId, groupCode);
        if (bussContactId == 0) {
            bussContactId = userService.findRandomUserIdByOrgCode(groupCode);
        }
        return bussContactId;
    }
}
